package com.example.linyiquan.app.util;

import android.content.Context;
import android.preference.PreferenceManager;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

/**
 * Created by linyiquan on 17-4-14.
 */

public class MyVolley {

    public static RequestQueue requestQueue;

    public interface OnResultListener {
        void done(JSONObject result);

        void fail(VolleyError error);
    }

    public static void init(Context context) {
        requestQueue = Volley.newRequestQueue(context);//添加RequstQueue的对象
    }

    //POST请求
    public static void post(String url, JSONObject params, final OnResultListener listener) {
        //创建JsonObjectRequst对象
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, params, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                listener.done(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                listener.fail(error);
            }
        });
        requestQueue.add(jsonObjectRequest);
        requestQueue.start();
    }

    //GET请求
    public static void get(String url, JSONObject params, final OnResultListener listener) {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, params, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                listener.done(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                listener.fail(error);
            }
        });
        requestQueue.add(jsonObjectRequest);
        requestQueue.start();
    }

}
